import React, { useEffect, useState } from 'react';
import { Select } from 'antd';
import type { IOptionType } from '../../type';
import 'moment/locale/zh-cn';
import styles from './index.less';

interface IProps {
  /**
   * 选择事件
   */
  onChange?: (values: any[]) => void;

  /**
   * 选项
   */
  options?: { label: string; value: string; children: IOptionType[] }[];
  /**
   * 选择值
   */
  value?: any[];
  /**
   * 禁用
   */
  disables?: boolean[];
  /**
   * 占位符
   */
  placeholders?: string[];
  /**
   * 是否可搜索
   */
  showSearchs?: boolean[];
}

const SelectGroup = (props: IProps) => {
  const {
    onChange,
    value: _value,
    options = [],
    disables = [false, false],
    showSearchs = [false, false],
    placeholders = ['请选择', '请选择'],
  } = props;
  const [value, setValue] = useState<any[]>([]);
  const [optionsTwo, setOptionsTwo] = useState<IOptionType[]>([]);

  useEffect(() => {
    if (_value) {
      setValue(_value);
      const arr = options.find((item) => item.value === _value[0]);
      setOptionsTwo(arr?.children || []);
    }
  }, [_value]);

  const _onChange = (data: any[]) => {
    onChange && onChange(data);
  };

  const onChangePeriodType = (e: string) => {
    const arr = options.find((item) => item.value === e);
    let data = [];
    if (e !== value[0]) {
      setValue([e]);
      data = [e];
    } else {
      setValue([e, value[1]]);
      data = [e, value[1]];
    }
    setOptionsTwo(arr?.children || []);
    _onChange(data);
  };

  const onChangePeriodDay = (e: string) => {
    setValue([value[0], e]);
    const data = [value[0], e];
    _onChange(data);
  };

  const filterOption = (input: string, option: { value: any; label: any }) => {
    const { label } = option;
    return label?.indexOf(input) >= 0;
  };

  return (
    <div className={styles.container}>
      <Select
        options={options}
        value={value[0]}
        onChange={onChangePeriodType}
        placeholder={placeholders[0] || '请选择'}
        disabled={disables[0] || false}
        style={{ marginRight: 12 }}
        showSearch={showSearchs[0]}
        filterOption={filterOption as any}
      />
      <Select
        options={optionsTwo as any}
        value={value[1]}
        onChange={onChangePeriodDay}
        showSearch={showSearchs[1]}
        disabled={disables[1] || false}
        placeholder={placeholders[0] || '请选择'}
        filterOption={filterOption as any}
      />
    </div>
  );
};

export default SelectGroup;
